package com.soft.javase.day14.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author yzh
 * @desc TODO
 * @date 2025/5/24
 */
public class ChatClient {
    public static void main(String[] args) {
        try (
                Socket socket = new Socket("127.0.0.1", 9999);
                PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                Scanner sc = new Scanner(System.in);
        ) {
            System.out.println("已连接到服务器（输入bye退出）:");

            new Thread(() -> {
                try {
                    String msg;
                    while ((msg = br.readLine()) != null) {
                        System.out.println("收到消息: " + msg);
                    }
                } catch (IOException e) {
                    System.out.println("与服务器的连接已断开");
                }
            }).start();

            String input;
            while (true) {
                input = sc.nextLine();
                pw.println(input);
                if (input.equalsIgnoreCase("bye")) {
                    break;
                }
            }
        } catch (IOException e) {
            System.out.println("连接服务器失败: " + e.getMessage());
        }
    }
}
